<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>bds日志查询</title>
    <link href="../css/bds/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="../css/bds/css/bootstrap-datetimepicker.css" rel="stylesheet" media="screen">
    <style>
        .bds-wrapper {
            width:1000px;
            margin: 0 auto;
        }
        .bds-form {
            padding-top: 100px;
        }

        .fr {
            float: right;
        }
    </style>
</head>
<body>
<div class="bds-wrapper">
    <form id="bdsLogSearchForm" class="form-horizontal bds-form">
        <div class="form-group">
            <label class="control-label col-sm-2" for="service">Service: </label>
            <div class="col-sm-10">
                <select id="service" class="form-control">
                    <option>hahaha</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2" for="module">Module: </label>
            <div class="col-sm-10">
                <select id="module" class="form-control">
                    <option>hahaha</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2">StartTime: </label>
            <div class='col-sm-10'>
                <div class='input-group date' id='startTime'>
                    <input type='text' class="form-control" />
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2" for="endTime">EndTime: </label>
            <div class='col-sm-10'>
                <div class='input-group date' id='endTime'>
                    <input type='text' class="form-control" />
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button id="submit" type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>
    <table class="table table-bordered">
        <thead>
        <tr id="tableHead">
        </tr>
        </thead>
        <tbody id="tbody">
        </tbody>
    </table>
    <nav class="fr">
      <ul class="pagination">
        <li>
          <a id="prev" href="#" aria-label="Previous">
            <span aria-hidden="true">上一页</span>
          </a>
        </li>
        <li>
          <a id="next" href="#" aria-label="Next">
            <span aria-hidden="true">下一页</span>
          </a>
        </li>
      </ul>
    </nav>
</div>
<script id="tableHeadTemplate">
</script>
<script src="../js/jquery-2.0.3.min.js"></script>
<script src="../js/bds/moment.js"></script>
<script src="../js/bds/bootstrap.min.js"></script>
<script src="../js/bds/bootstrap-datetimepicker.js"></script>
<script src="../js/jquery.twbsPagination.min.js"></script>
<script src="../js/template-native.js"></script>
<script type="text/javascript">
    /** * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
        可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
        Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
     * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
     * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
     * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
     * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
     */
    Date.prototype.pattern=function(fmt) {
        var o = {
        "M+" : this.getMonth()+1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
        "H+" : this.getHours(), //小时
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S" : this.getMilliseconds() //毫秒
        };
        var week = {
        "0" : "/u65e5",
        "1" : "/u4e00",
        "2" : "/u4e8c",
        "3" : "/u4e09",
        "4" : "/u56db",
        "5" : "/u4e94",
        "6" : "/u516d"
        };
        if(/(y+)/.test(fmt)){
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        if(/(E+)/.test(fmt)){
            fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);
        }
        for(var k in o){
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    }

    $(function () {

        var $submitBtn = $('#submit'),
            $service = $('#service'),
            $module = $('#module'),
            $startTime = $('#startTime'),
            $endTime = $('#endTime'),
            maxId = 0,
            minId = 0;

        // 初始化datetimepicker
        $startTime.datetimepicker({
            defaultDate: new Date()
        });

        $endTime.datetimepicker({
            defaultDate: new Date()
        });

        var tableHeadHtml = [
            '<th style="width: 200px;">时间</th>',
            '<% for(var i in columns) {%>',
            '<th><%= i %></th>',
            '<% }%>'
        ].join('');

        var tableTrHtml = [
                '<tr>',
                '<td><%= dateStr %></td>',
                '<% for(var i in columns) {%>',
                '<td><%= log[i] || "" %></td>',
                '<% }%>',
                '</tr>'
        ].join('');


        var tableHeadTemplate = template.compile(tableHeadHtml),
            tableTrTemplate = template.compile(tableTrHtml);



        $submitBtn.on('click', function(e) {
            e.preventDefault();
            $.ajax({
                url: '/bds/bdsQuery.php',
                data: {
                    service: $.trim($service.val()),
                    module: $.trim($module.val()),
                    start_time: parseInt(+$startTime.data('DateTimePicker').date()._d, 10),
                    end_time: parseInt(+$endTime.data('DateTimePicker').date()._d, 10)
                },
                type: 'POST',
                dataType: 'json'
            })
                    .done(function (res) {
                        if(res && res.logs.length !== 0) {
                            var logs = res.logs;
                            renderLog(logs);

                        } else {
                            alert('请求失败！');
                        }
                    })
                    .fail(function() {
                        alert('请求失败！');
                    });
        });

        var renderLog = function(logs) {

            if(logs.length !== 0) {
                maxId = logs[logs.length - 1].id;
                minId = logs[0].id;
            }

            // first dealing with the thead
            // 获取一共有多少个列
            var columns = {},
                totalHtml = '';
            for(var i = 0, len = logs.length; i < len; i++) {
                var log = logs[i];
                for(var column in log) {
                    // 新增对应column值
                    columns[column] = 1;
                }
            }
            // 到这一步就获取了所有要显示的column了
            // 通过template将之加入到thead处
            $('#tableHead').html(tableHeadTemplate({ columns: columns }));


            for(var i = 0, len = logs.length; i < len; i++) {
                var logDate = new Date(+logs[i].ts),
                        log = logs[i],
                        dateStr = logDate.pattern('yyyy/MM/dd hh:mm:ss');

                totalHtml += tableTrTemplate({ dateStr: dateStr, columns: columns, log: log });
            }

            $('#tbody').html(totalHtml);
        }
    });
</script>
<script>
</script>
</body>
</html>